<!DOCTYPE html>
<html>
<head>
    <title>噬天灵诀·天龙逐珠</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <style>

        /* 保持自动模式容器高度稳定 */
        #autoModeLabel {
            display: inline-block;
            visibility: visible;
        }
        
        /* 新增固定高度的容器层 */
        .control-container {
            height: 56px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #gameCanvas {
            border: 2px solid #333;
        }
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f0f0f0;
        }

        /* 修改后的得分容器样式 */
        .score-container {
            display: flex;
            justify-content: space-between;
            width: 100%;
            max-width: 400px;
            margin: 1px 0;
        }
        #score, #highscore {
            flex: 1;
        }
        #highscore {
            text-align: right;
            margin-left: auto; /* 确保始终右对齐 */
        }
        
        /* 添加移动端适配 */
        @media (max-width: 480px) {
            .score-container {
                gap: 10px;
                max-width: 90%;
            }
            #score, #highscore {
                font-size: 14px;
            }
        }
        
        /* 修改后的摇杆样式 */
        #joystick {
            position: relative;
            width: 120px;
            height: 120px;
            margin: 20px auto;
            touch-action: none;
            background: rgba(173, 216, 230, 0.1); /* 添加浅蓝色背景 */
            border-radius: 50%; /* 圆形背景 */
            box-shadow: 0 0 15px rgba(135, 206, 235, 0.3); /* 添加光晕效果 */
        }
        .direction-btn {
            position: absolute;
            width: 40px;
            height: 40px;
            background: #87CEEB; /* 浅蓝色 */
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s; /* 添加过渡效果 */
            box-shadow: 2px 2px 5px rgba(0,0,0,0.2); /* 立体阴影 */
            border: 2px solid #6CB2D6; /* 添加边框 */
        }
        #centerBtn {
            position: absolute;
            left: 40px;
            top: 40px;
            background: #6CB2D6; /* 深一点的蓝色 */
            box-shadow: inset 0 0 8px rgba(0,0,0,0.1); /* 内阴影 */
            border: 2px solid #4F9CB8; /* 更深的边框 */
        }
        /* 添加悬停效果 */
        .direction-btn:hover, 
        .direction-btn.active-direction { /* 新增激活状态样式 */
            background: #6CB2D6;
            transform: scale(1.1);
        }

    </style>
</head>
<body>
    <!-- 修改标题容器 -->
    <div style="text-align: center; margin: 10px 0">
        <h1 style="color: #2c3e50; font-size: 1.5em; text-shadow: 2px 2px 4px rgba(0,0,0,0.2)">《噬天灵诀·天龙逐珠》</h1>
        <h5 style="color: #7f8c8d; font-style: italic; margin-top: -8px; margin-bottom: -8px">九霄自循灵珠秘法 ——by Tino Zhong</h5>
    </div>
    
    <!-- 修改得分显示为水平布局 -->
    <div class="score-container">
        <div id="score">得分: 0</div>
        <div>
            <label id="autoModeLabel">
                <input type="checkbox" id="autoMode"> 自循灵珠
            </label>
        </div>
        <div id="highscore">最高分: 0</div>
    </div>

    <div style="display: flex; justify-content: space-between; align-items: center; width: 100%; max-width: 400px">
        <div style="flex: 1; min-width: 200px; display: flex; align-items: center; gap: 8px">
            <label style="white-space: nowrap">速度(ms):</label>
            <input type="range" id="speed" min="0" max="500" value="500" step="50" style="flex: 1">
            <span id="speedValue" style="min-width: 40px; text-align: left">500</span>
        </div>
        
        <div style="margin: 5px">
            <label>
                <input type="checkbox" id="soundToggle" checked> 音效
            </label>
        </div>
    </div>
    
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    
    <!-- 新增触摸摇杆 -->
    <div id="joystick">
        <div class="direction-btn" style="left:40px; top:0" data-dir="up">↑</div>
        <div class="direction-btn" style="right:0; top:40px" data-dir="right">→</div>
        <div class="direction-btn" style="left:0; top:40px" data-dir="left">←</div>
        <div class="direction-btn" style="left:40px; bottom:0" data-dir="down">↓</div>
        <div id="centerBtn" class="direction-btn" data-dir="center">●</div>
    </div>

    <script>
        let soundEnabled = true; // 新增音效状态
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const highScoreElement = document.getElementById('highscore');  // 添加最高分元素引用
        // 加载最高分
        let highScore = 0;
        //let highScore = localStorage.getItem('snakeHighScore') || 0;
        highScoreElement.textContent = `最高分: ${highScore}`;

        const gridSize = 20;
        const tileCount = canvas.width / gridSize;
    
        let snake = [
            { x: 10, y: 10 }
        ];
        let food = { x: 15, y: 15 };
        let dx = 0;
        let dy = 0;
        let score = 0;
        let gameLoop;

        // 新增音效开关监听
        document.getElementById('soundToggle').addEventListener('change', function() {
            soundEnabled = this.checked;
        });

        // 添加自动模式元素引用
        const autoModeCheckbox = document.getElementById('autoMode');
        
        // 添加速度控制元素引用
        const speedControl = document.getElementById('speed');
        const speedValue = document.getElementById('speedValue');
    
        // 修改后的开始游戏函数（唯一版本）
        function startGame() {
            if (gameLoop) clearInterval(gameLoop);
            const speed = parseInt(speedControl.value);
            gameLoop = setInterval(update, speed);
        }

        // 添加速度控制事件监听
        speedControl.addEventListener('input', function() {
            speedValue.textContent = this.value;
            if (gameLoop) {
                startGame();
            }
        });
    
        document.addEventListener('keydown', changeDirection);
    
        function draw() {
            // 清空画布
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
        
            // 先绘制灵珠（解决覆盖问题）
            const foodX = food.x * gridSize + gridSize/2;
            const foodY = food.y * gridSize + gridSize/2;
            const radius = gridSize/2 - 2;
            
            // 灵珠光晕效果
            const gradient = ctx.createRadialGradient(foodX, foodY, 1, foodX, foodY, radius*1.2);  // 扩大光晕范围
            gradient.addColorStop(0, 'rgba(255,255,255,0.8)');
            gradient.addColorStop(0.5, 'rgba(70,130,180,0.8)');
            gradient.addColorStop(1, 'rgba(25,25,112,0.8)');
        
            // 绘制灵珠主体
            ctx.beginPath();
            ctx.arc(foodX, foodY, radius*1.15, 0, Math.PI * 2);  // 半径增大15%
            ctx.fillStyle = gradient;
            ctx.shadowColor = 'darkblue';
            ctx.shadowBlur = 10;
            ctx.fill();
        
            // 添加高光点
            ctx.beginPath();
            ctx.arc(foodX - 4, foodY - 4, 3, 0, Math.PI * 2);
            ctx.fillStyle = 'rgba(255,255,255,0.9)';
            ctx.fill();
        
            // 后绘制龙身
            snake.forEach((segment, index) => {
                const x = segment.x * gridSize;
                const y = segment.y * gridSize;
                const size = gridSize - 2;
                
                // 龙身颜色（头部深橙色，身体渐变橙色）
                const gradient = ctx.createLinearGradient(x, y, x + size, y + size);
                gradient.addColorStop(0, index === 0 ? '#FF8C00' : '#FFA500');
                gradient.addColorStop(1, index === 0 ? '#FF4500' : '#FF6347');
            
                // 绘制方块身体
                ctx.fillStyle = gradient;
                ctx.fillRect(x, y, size, size);
            
                // 绘制龙头特征
                if(index === 0) {
                    ctx.strokeStyle = '#8B4513';
                    ctx.lineWidth = 2;
                    
                    // 方向计算（示例向右方向）
                    const baseAngle = dx === 1 ? Math.PI : 
                                    dx === -1 ? 0 :
                                    dy === 1 ? -Math.PI/2 : Math.PI/2;
                    
                    // 新增眼睛绘制
                    const eyeOffset = gridSize/4;  // 眼睛偏移量
                    const eyeRadius = 3;          // 眼睛半径
                    
                    // 新增眼睛前移系数
                    const forwardOffset = - gridSize/10;  // 前移量为格子大小的1/10
                    
                    // 新增胡须独立前移系数
                    const whiskerForwardOffset = - gridSize/3;  // 胡须前移量

                    // 绘制左眼（添加前进方向偏移）
                    ctx.beginPath();
                    ctx.arc(
                        x + gridSize/2 + Math.cos(baseAngle) * forwardOffset + Math.cos(baseAngle + Math.PI/2) * eyeOffset,
                        y + gridSize/2 + Math.sin(baseAngle) * forwardOffset + Math.sin(baseAngle + Math.PI/2) * eyeOffset,
                        eyeRadius, 0, Math.PI*2
                    );
                    ctx.fillStyle = '#00BFFF';  // 改为亮蓝色
                    ctx.fill();
                    
                    // 绘制右眼（添加前进方向偏移）
                    ctx.beginPath();
                    ctx.arc(
                        x + gridSize/2 + Math.cos(baseAngle) * forwardOffset + Math.cos(baseAngle - Math.PI/2) * eyeOffset,
                        y + gridSize/2 + Math.sin(baseAngle) * forwardOffset + Math.sin(baseAngle - Math.PI/2) * eyeOffset,
                        eyeRadius, 0, Math.PI*2
                    );
                    ctx.fillStyle = '#00BFFF';  // 改为亮蓝色
                    ctx.fill();
                    
                    // 新增胡须绘制
                    const whiskerLength = 12;
                    const whiskerAngle = Math.PI/2 + Math.PI/6;

                    // 右胡须（增加180度旋转）
                    drawWhisker(
                        x + gridSize/2 + Math.cos(baseAngle) * whiskerForwardOffset + Math.cos(baseAngle + Math.PI/2) * eyeOffset,
                        y + gridSize/2 + Math.sin(baseAngle) * whiskerForwardOffset + Math.sin(baseAngle + Math.PI/2) * eyeOffset,
                        baseAngle - whiskerAngle + Math.PI,  // 增加180度旋转
                        whiskerLength
                    );
                    
                    // 左胡须（增加180度旋转）
                    drawWhisker(
                        x + gridSize/2 + Math.cos(baseAngle) * whiskerForwardOffset + Math.cos(baseAngle - Math.PI/2) * eyeOffset,
                        y + gridSize/2 + Math.sin(baseAngle) * whiskerForwardOffset + Math.sin(baseAngle - Math.PI/2) * eyeOffset,
                        baseAngle + whiskerAngle + Math.PI,  // 增加180度旋转
                        whiskerLength
                    );

                    // 绘制龙角
                    // 修改龙角偏移方向为平行头部方向
                    const offset = gridSize/3 * 0.9;
                    const angleOffset = Math.PI/4;

                    // 右侧龙角（使用平行方向）
                    drawAntenna(
                        x + gridSize/2 + Math.cos(baseAngle + Math.PI/2) * offset,  // 从 Math.PI/2 改为 0
                        y + gridSize/2 + Math.sin(baseAngle) * offset,
                        baseAngle + angleOffset,
                        15
                    );
                    
                    // 左侧龙角（使用平行方向）
                    drawAntenna(
                        x + gridSize/2 + Math.cos(baseAngle - Math.PI/2) * offset, 
                        y + gridSize/2 + Math.sin(baseAngle) * offset,
                        baseAngle - angleOffset,
                        15
                    );

                }
                else if(index == snake.length - 1)
                {
                    // 修正龙尾绘制逻辑
                    const tail = snake[snake.length - 1];
                    const prevSegment = snake[snake.length - 2];
                    
                    ctx.save();
                    ctx.translate(tail.x * gridSize + gridSize/2, tail.y * gridSize + gridSize/2);
                    
                    let rotation = -Math.PI/2;      //尾默认向下。
                    if (prevSegment) {
                        const deltaX = tail.x - prevSegment.x;
                        const deltaY = tail.y - prevSegment.y;
                        
                        if (deltaX === 1) rotation = Math.PI;        // 向左旋转180度
                        else if (deltaX === -1) rotation = 0;        // 保持原方向
                        else if (deltaY === 1) rotation = -Math.PI/2; // 向上旋转90度
                        else if (deltaY === -1) rotation = Math.PI/2; // 向下旋转90度

                    } else {
                        // 当只有龙头时，根据移动方向设置旋转
                        if (dx === 1) rotation = 0;        // 向右移动时箭头朝右
                        else if (dx === -1) rotation = Math.PI;       // 向左移动时箭头朝左
                        else if (dy === 1) rotation = Math.PI/2;     // 向下移动时箭头朝下 
                        else if (dy === -1) rotation = -Math.PI/2;   // 向上移动时箭头朝上
                    }

                    ctx.rotate(rotation);
                    
                    // 新增渐变尾鳍
                    const gradient = ctx.createLinearGradient(-15, 0, 15, 0);
                    gradient.addColorStop(0, '#FF4500');
                    gradient.addColorStop(0.5, '#FF6347');
                    gradient.addColorStop(1, '#FF8C00');
                    
                    // 绘制尾鳍菱形（修正顶点顺序）
                    ctx.beginPath();
                    ctx.moveTo(-gridSize/3, 0);
                    ctx.lineTo(-gridSize*1, gridSize/3);   // 上侧顶点
                    ctx.lineTo(-gridSize*1.5, 0);            // 最远点
                    ctx.lineTo(-gridSize*1, -gridSize/3);  // 下侧顶点
                    ctx.closePath();

                    // 添加立体效果
                    ctx.shadowColor = 'rgba(0,0,0,0.3)';
                    ctx.shadowBlur = 5;
                    ctx.shadowOffsetY = 2;
                    ctx.fillStyle = gradient;
                    ctx.fill();
                    
                    ctx.restore();
                }
            });
    
        }
    
        // 修正龙角角度计算
        function drawAntenna(baseX, baseY, angle, length) {
            const endX = baseX + Math.cos(angle) * length;
            const endY = baseY + Math.sin(angle) * length;
        
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(baseX, baseY);
            ctx.lineTo(endX, endY);
            ctx.stroke();
            
            // 新增分叉绘制 (长度为主角的2/3)
            const forkAngle1 = angle + Math.PI/8;  // 增加15度分叉角度
            const forkAngle2 = angle - Math.PI/8;
            ctx.moveTo(endX, endY);
            ctx.lineTo(endX + Math.cos(forkAngle1) * length*0.66, endY + Math.sin(forkAngle1) * length*0.66);
            ctx.moveTo(endX, endY);
            ctx.lineTo(endX + Math.cos(forkAngle2) * length*0.66, endY + Math.sin(forkAngle2) * length*0.66);
            ctx.stroke();
            
            ctx.restore();
        }
    
        // 新增胡须绘制函数
        function drawWhisker(baseX, baseY, angle, length) {
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(baseX, baseY);
            ctx.lineTo(
                baseX + Math.cos(angle) * length,
                baseY + Math.sin(angle) * length
            );
            ctx.strokeStyle = 'rgba(255,215,0,0.9)';  // 改为金色
            ctx.lineWidth = 1.5;
            ctx.shadowColor = 'rgba(0,0,0,0.3)';
            ctx.shadowBlur = 3;
            ctx.stroke();
            ctx.restore();
        }

        // 修改后的方向控制函数
        function changeDirection(event) {
            const LEFT_KEY = 37;
            const RIGHT_KEY = 39;
            const UP_KEY = 38;
            const DOWN_KEY = 40;
            const SPACE_KEY = 32; 
            
            const keyPressed = event.keyCode;
            const currentDX = dx;
            const currentDY = dy;
        
            // 新增空格键处理
            if (keyPressed === SPACE_KEY) {
                event.preventDefault();
                if(gameLoop) {
                    clearInterval(gameLoop);
                    gameLoop = null;
                    autoModeCheckbox.parentElement.style.visibility = 'visible'; // 改用 visibility
                } else {
                    startGame();
                    autoModeCheckbox.parentElement.style.visibility = autoModeCheckbox.checked ? 'hidden' : 'visible';
                }

                document.querySelector('#centerBtn').classList.add('active-direction');
                setTimeout(() => {
                    document.querySelector('#centerBtn').classList.remove('active-direction');
                }, 100);
                return;
            }
        
            if (keyPressed === LEFT_KEY && currentDX !== 1) {  // 禁止向右时立即向左
                dx = -1;
                dy = 0;
                startGame();
            }
            if (keyPressed === UP_KEY && currentDY !== 1) {    // 禁止向下时立即向上
                dx = 0;
                dy = -1;
                startGame();
            }
            if (keyPressed === RIGHT_KEY && currentDX !== -1) { // 禁止向左时立即向右
                dx = 1;
                dy = 0;
                startGame();
            }
            if (keyPressed === DOWN_KEY && currentDY !== -1) {  // 禁止向上时立即向下
                dx = 0;
                dy = 1;
                startGame();
            }

            // 在方向变化后更新指示器
            if (dx !== currentDX || dy !== currentDY) {
                updateDirectionIndicator();
            }
        }
    
        function generateFood() {
            // 使用循环代替递归防止栈溢出
            let newFood;
            const maxAttempts = 1000; // 防止无限循环的安全措施
            let attempts = 0;
            
            do {
                newFood = {
                    x: Math.floor(Math.random() * tileCount),
                    y: Math.floor(Math.random() * tileCount)
                };
                attempts++;
            } while (
                snake.some(segment => segment.x === newFood.x && segment.y === newFood.y) && 
                attempts < maxAttempts
            );
    
            food = newFood;
            
            // 添加安全校验（当蛇占满地图时）
            if (attempts >= maxAttempts) {
                console.error("无法找到合适的食物位置");
            }
        }
    
        function isGameOver() {
            // 撞墙检测
            if (snake[0].x < 0 || snake[0].x >= tileCount || 
                snake[0].y < 0 || snake[0].y >= tileCount) {
                return true;
            }
            
            // 自撞检测
            for (let i = 1; i < snake.length; i++) {
                if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
                    return true;
                }
            }
            return false;
        }
    
        function gameOver() {
            clearInterval(gameLoop);
            gameLoop = null;
            
            // 更新最高分
            if (score > highScore) {
                highScore = score;
                //localStorage.setItem('snakeHighScore', highScore);
                highScoreElement.textContent = `最高分: ${highScore}`;

                // 破纪录音效
                if (soundEnabled) {
                    new Audio('sfx/newscore.mp3').play().catch(() => {});
                }
            }
            else
            {
                // 游戏结束音效
                if (soundEnabled) { // 新增条件检查
                    new Audio('sfx/gameover.mp3').play().catch(() => {});
                }
            }
            scoreElement.textContent = `得分:${score}游戏结束！`;
            
            setTimeout(() => {
                snake = [{ x: 10, y: 10 }];
                dx = 0;
                dy = 0;
                score = 0;
                generateFood();
                draw();
                scoreElement.textContent = `得分: ${score}`;
                if (autoModeCheckbox.checked) {
                    startGame();
                }
            }, 2000);
        }
    
        // 新增自动导航相关函数（放在update函数之前）
        function autoNavigate() {
            if (!autoModeCheckbox.checked) return;
            
            const prevDX = dx;
            const prevDY = dy;

            const head = snake[0];
            const safeDirections = calculateSafeDirections(head);
            const bestDirection = findBestDirection(head, food, safeDirections);
            
            if (bestDirection) {
                [dx, dy] = bestDirection;
            }

            // 检测方向是否变化
            if (dx !== prevDX || dy !== prevDY) {
                updateDirectionIndicator();
            }
        }

        function calculateSafeDirections(head) {
            const directions = [];
            if (!willCollide(head.x - 1, head.y)) directions.push([-1, 0]);
            if (!willCollide(head.x + 1, head.y)) directions.push([1, 0]);
            if (!willCollide(head.x, head.y - 1)) directions.push([0, -1]);
            if (!willCollide(head.x, head.y + 1)) directions.push([0, 1]);
            return directions;
        }

        function willCollide(x, y) {
            return x < 0 || x >= tileCount || y < 0 || y >= tileCount || 
                snake.some(seg => seg.x === x && seg.y === y);
        }

        // 修改后的update函数（保持原有逻辑）
        function update() {
            autoNavigate(); // 添加自动导航
            const head = { x: snake[0].x + dx, y: snake[0].y + dy };
            
            if (head.x === food.x && head.y === food.y) {
                if (soundEnabled) { // 新增条件检查
                    const eatSound = new Audio('sfx/eat.mp3');
                    eatSound.play().catch(() => {});
                }

                score += 10;
                scoreElement.textContent = `得分: ${score}`;
                generateFood();
            } else {
                snake.pop();
            }
            
            snake.unshift(head);
        
            if (isGameOver()) {
                gameOver();
                return;
            }
        
            draw();
        }
        
        // 修改方向指示器函数（添加延时恢复）
        let activeTimeout;
        function updateDirectionIndicator() {
            // 清除之前的定时器
            if (activeTimeout) clearTimeout(activeTimeout);

            document.querySelectorAll('.direction-btn').forEach(btn => {
                btn.classList.remove('active-direction');
                
                const dir = btn.dataset.dir;
                if ((dir === 'up' && dy === -1) || 
                    (dir === 'down' && dy === 1) ||
                    (dir === 'left' && dx === -1) || 
                    (dir === 'right' && dx === 1)) {
                    btn.classList.add('active-direction');
                }
            });

            // 设置100ms后恢复
            activeTimeout = setTimeout(() => {
                document.querySelectorAll('.direction-btn').forEach(btn => {
                    btn.classList.remove('active-direction');
                });
            }, 100);
        }

        // 修改自动模式切换监听
        autoModeCheckbox.addEventListener('change', function() {
            if (this.checked) {
                this.parentElement.style.visibility = 'hidden';
                speedControl.value = 200;  
                speedControl.dispatchEvent(new Event('input'));
                startGame();
            } else {
                this.parentElement.style.visibility = 'visible';
                speedControl.value = 500;
                speedControl.dispatchEvent(new Event('input'));
                if(gameLoop) {  
                    clearInterval(gameLoop);
                    gameLoop = null;
                }
            }
        });

        // 新增摇杆事件处理
        const joystick = document.getElementById('joystick');
        let activeDirection = null;

        // 修复触摸事件处理（替换原有handleControl）
        function handleJoystickStart(e) {
            e.preventDefault();
            const touch = e.touches?.[0] || e;
            const elements = document.elementsFromPoint(touch.clientX, touch.clientY);
            const btn = elements.find(el => el.classList.contains('direction-btn'));
            
            const prevDX = dx;
            const prevDY = dy;

            if (btn) {
                const dir = btn.dataset.dir;
                switch(dir) {
                    case 'up': 
                        if (dy !== 1) { dx = 0; dy = -1; }
                        break;
                    case 'down': 
                        if (dy !== -1) { dx = 0; dy = 1; }
                        break;
                    case 'left': 
                        if (dx !== 1) { dx = -1; dy = 0; }
                        break;
                    case 'right': 
                        if (dx !== -1) { dx = 1; dy = 0; }
                        break;
                    case 'center':
                        if(gameLoop) {
                            clearInterval(gameLoop);
                            gameLoop = null;
                            autoModeCheckbox.parentElement.style.visibility = 'visible';
                        } else {
                            startGame();
                            autoModeCheckbox.parentElement.style.visibility = 
                                autoModeCheckbox.checked ? 'hidden' : 'visible';
                        }
                        document.querySelector('#centerBtn').classList.add('active-direction');
                        setTimeout(() => {
                            document.querySelector('#centerBtn').classList.remove('active-direction');
                        }, 100);
                        return;
                }
            }
            
            // 仅在方向变化时启动游戏
            if (dx !== prevDX || dy !== prevDY) {
                startGame();
                updateDirectionIndicator();
            }
        }

        // 添加事件监听
        joystick.addEventListener('touchstart', handleJoystickStart);
        joystick.addEventListener('mousedown', handleJoystickStart);
        
        // 初始化游戏
        generateFood();
        draw();

        
        function findBestDirection(head, food, directions) {
            if (directions.length === 0) return null;
            
            // 新增：检测是否有蛇身段在顶部行
            const hasSegmentInTopRow = snake.some(segment => segment.y === 0);
            
            const pathEvaluations = directions.map(dir => {
                const nextX = head.x + dir[0];
                const nextY = head.y + dir[1];
                const isFoodNext = nextX === food.x && nextY === food.y;
                let distance = Math.abs(nextX - food.x) + Math.abs(nextY - food.y);
                const isUp = dir[1] === -1;
            
            // 新增避开顶部逻辑：如果已有蛇身在顶部且不是去吃食物
            if (hasSegmentInTopRow && isUp && !isFoodNext) {
                distance += 1000; // 增加距离惩罚值
            }
            
                return {
                    dir,
                    distance,
                    safeSpace: calculateSafeSpace(nextX, nextY)
                };
            });
            
            const safePaths = pathEvaluations.filter(p => p.safeSpace >= snake.length + 2);
            if (safePaths.length > 0) {
                return safePaths.reduce((a, b) => (a.distance < b.distance ? a : b), safePaths[0]).dir;
            }
            
            return pathEvaluations.reduce((a, b) => {
                const scoreA = a.safeSpace * 1000 - a.distance;
                const scoreB = b.safeSpace * 1000 - b.distance;
                return scoreA > scoreB ? a : b;
            }, pathEvaluations[0] || {}).dir;
        }

        // 新增安全空间计算函数
        function calculateSafeSpace(x, y) {
            const visited = new Set();
            const queue = [[x, y]];
            let space = 0;

            while (queue.length > 0) {
                const [cx, cy] = queue.shift();
                const key = `${cx},${cy}`;
                
                if (visited.has(key)) continue;
                if (willCollide(cx, cy)) continue;
                
                visited.add(key);
                space++;
                
                // 四方向扩展
                [[1,0], [-1,0], [0,1], [0,-1]].forEach(([dx, dy]) => {
                    queue.push([cx + dx, cy + dy]);
                });
            }
            return space;
        }

        //添加音效配置
        // const SOUND_MAPPING = {
        //     'up': 'sfx/up.mp3',
        //     'down': 'sfx/down.mp3',
        //     'left': 'sfx/left.mp3',
        //     'right': 'sfx/right.mp3',
        //     'center': 'sfx/click.mp3'
        // };

        // 音效可以从 爱给网 这里找：
        // https://www.aigei.com/
        const SOUND_MAPPING = {
            'up': 'sfx/click.mp3',
            'down': 'sfx/click.mp3',
            'left': 'sfx/click.mp3',
            'right': 'sfx/click.mp3',
            'center': 'sfx/click.mp3'
        };
        const audioCache = new Map(); // 新增音频缓存

        // 添加 MutationObserver 监听类变化
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                if (!soundEnabled) return; // 新增音效开关检查

                if (mutation.attributeName === 'class') {
                    const btn = mutation.target;
                    const isActive = btn.classList.contains('active-direction');
                    
                    // 获取或创建音频对象
                    if (!audioCache.has(btn.dataset.dir)) {
                        audioCache.set(btn.dataset.dir, new Audio(SOUND_MAPPING[btn.dataset.dir]));
                    }
                    const audio = audioCache.get(btn.dataset.dir);

                    if (isActive) {
                        audio.currentTime = 0; // 重置播放进度
                        audio.play().catch(() => {});
                    }
                }
            });
        });

        // 为所有方向按钮添加监听
        document.querySelectorAll('.direction-btn').forEach(btn => {
            observer.observe(btn, { attributes: true });
        });
    </script>
</body>
</html>
